package com.mh.controller;

import com.mh.dto.R;
import com.mh.service.MbtiTestService;
import com.mh.utils.CommonUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.util.Map;

/**
 * Date:2024/9/26
 * author:zmh
 * description: 通用接口
 **/

@RestController
@CrossOrigin
@RequestMapping("/common")
@Slf4j
@RequiredArgsConstructor
public class CommonController {

    @Value("${file_path}")
    private String docPath;

    @Value("${wxPay.appId}")
    private String appId;

    @Value("${wxPay.appSecret}")
    private String appSecret;

    private final MbtiTestService mbtiTestService;

    /**
     * 导入题库
     * @return ·
     */
    @GetMapping("/importTopics")
    public R<String> importTopics(){
        mbtiTestService.importMbtiTestData("D:\\mbti.txt");
        return null;
    }

    /**
     * 获取openID
     * @param code 登录临时码 - 用于换取openId
     * @return 用户openID
     */
    @GetMapping("/getOpenId/{code}")
    public ResponseEntity<?> getOpenId(@PathVariable String code) {
        String url = String.format(
                "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                appId, appSecret, code);

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);

        // 解析返回的 JSON 数据
        String openId = CommonUtil.extractOpenId(response.getBody());
        return ResponseEntity.ok(Map.of("openid", openId));
    }

    /**
     * 获取md文档
     * @return 返回md文档
     * @throws  ·
     */
    @GetMapping("/download")
    public ResponseEntity<Resource> getImage(String docName) {
        // 处理目录路径拼接问题
        docName = docName.replace("$", "/");
        String fullDocName = docPath + docName; // docPath为md文档所在文件夹
        log.info("获取md文档路径==>{}", fullDocName);

        File file = new File(fullDocName);
        if (!file.exists()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }

        Resource resource = new FileSystemResource(file);
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getName() + "\"");

        return ResponseEntity.ok()
                .headers(headers)
                .body(resource);
    }
}
